<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--侧边部门数据-->
      <a-col :xs="9" :sm="6" :md="5" :lg="4" :xl="4">
        <div class="head-container">
          <a-input
            v-model="deptName"
            clearable
            placeholder="输入部门名称搜索"
            prefix-icon="el-icon-search"
            class="filter-item"
            @search="getDeptDatas"
          />
        </div>
        <a-tree
          v-model="checkedKeys"
          multiple
          :load-data="onLoadData"
          :tree-data="treeData"
        />
      </a-col>
      <!--用户数据-->
      <el-col :xs="15" :sm="18" :md="19" :lg="20" :xl="20">
        <!--工具栏-->
        <div class="head-container">
          <a-button v-permission="permission.add" class="filter-item" type="primary" icon="plus" @click="crudCreate" >新增</a-button>
        </div>
        <!--表格渲染-->
        <a-table
            size="middle"
            row-key="id"
            :columns="columns"
            :data-source="tableData"
            :pagination="ipagination"
            :loading="loading"
            :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
            :customRow="customRow"
            @change="handleTableChange"
          >
            <span slot="action" slot-scope="text, record" >
              <udOperation
                :data="record"
                :permission="permission"
                :disabled-dle="record.id === 1"
                @crudUpdate="crudUpdate"
                @crudDelete="crudDelete(record.id)"
              />
            </span>
          </a-table>
      </el-col>
    </el-row>
    <!-- 弹窗渲染 -->
    <user-update-modal ref="updateForm" @closeModal="closeModal"></user-update-modal>
  </div>
</template>

<script>
import ApiTree from '@/api/system/user'
import { Slime, crud } from '@/mixins/slime';
import UserUpdateModal from './userUpdateModal';

import { isvalidPhone } from '@/utils/validate'
import { getDeptTree } from '@/api/system/dept'
import { getAll } from '@/api/system/role'
import udOperation from '@crud/UD.operation'
import { mapGetters } from 'vuex'
let userRoles = []
export default {
  name: 'User',
  components: { udOperation, UserUpdateModal, },
  mixins: [Slime],
  // 数据字典
  // dicts: ['user_status'],
  data() {
    // 自定义验证
    const validPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入电话号码'))
      } else if (!isvalidPhone(value)) {
        callback(new Error('请输入正确的11位手机号码'))
      } else {
        callback()
      }
    }
    return {
      //tree
      treeData:[],
      checkedKeys: [], //最后的值
      // table
      tableData: [],
      columns: [
        {
          title: '用户名',
          align: 'left',
          dataIndex: 'username',
        },
        {
          title: '昵称',
          align: 'left',
          dataIndex: 'nickname',
        },
        {
          title: '电话',
          align: 'left',
          dataIndex: 'mobile',
        },
        {
          title: '部门',
          align: 'left',
          dataIndex: 'deptCode',
        },
        {
          title: '创建日期',
          align: 'left',
          dataIndex: 'createTime',
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' },
        },
      ],
      //
      height: document.documentElement.clientHeight - 180 + 'px;',
      deptName: '', depts: [], deptDatas: [], level: 3, roles: [],
      roleDatas: [], // 多选时使用
      deptCode: null,
      defaultProps: { children: 'children', label: 'name', isLeaf: 'leaf' },
      permission: {
        add: ['admin', 'user:add'],
        edit: ['admin', 'user:edit'],
        del: ['admin', 'user:del']
      },
    }
  },
  computed: {
    ...mapGetters([
      'user'
    ])
  },
  created() {
    // this.crud.msg.add = '新增成功，默认密码：123456'
    crud(ApiTree)
    this.loadData();
    this.funTreeData();
  },
  mounted: function() {
    const that = this
    window.onresize = function temp() {
      that.height = document.documentElement.clientHeight - 180 + 'px;'
    }
  },
  methods: {
    // 加载表格数据
    loadData(arg) {
      this.loadDataPack(arg).then((res) => {
        let tableData = [];
        if (res.result) {
          tableData = res.result.records;
        }
        this.tableData = tableData;
      });
    },
    // tree初始化
    funTreeData(){
      getDeptTree(0).then((res) => {
        let data = res.result;
        const treeData = data.map(function (item) {
          if (item.subCount > 0) {
            item = { ...item, children: [], key: item.id, title: item.name};
          }else{
            item = { ...item, key: item.id, title: item.name, isLeaf: true,};
          }
          return item;
        });
        this.treeData = treeData;
        console.log('treeData',treeData)
      });
    },
    // tree点击加载下级
    onLoadData(treeNode){
      return new Promise(resolve => {
        getDeptTree(treeNode.dataRef.id).then((res) => {
          let data = res.result;
          const tableData = data.map(function (item) {
            if (item.subCount > 0) {
              item = { ...item, children: [], key: item.id};
            }else{
              item = { ...item, isLeaf: true, key: item.id, title: item.name};
            }
            return item;
          });
          treeNode.dataRef.children = tableData
          this.treeData = [...this.treeData];
          resolve();
        });
      });
    },
    // 点击单行
    customRow(record){
      return {
        on: { 
          // 事件点击行
          click: (event) => {
            if (record) {
              // ApiTree.menuIds(record.id).then((res) => {
              //   console.log("treeData",this.treeData)
              //   this.checkedKeys = res.result;
              //   this.showButton = true;
              //   this.roleId = record.id;
              // });
            }
          },       
        },
      };
    },


    // 弹窗-改动角色
    changeRole(value) {
      console.log(value)
      userRoles = []
      userRoles = value
    },
    // 弹窗-移除角色
    deleteTag(value) {
      userRoles.forEach(function(data, index) {
        if (data === value) {
          userRoles.splice(index, value)
        }
      })
    },
    // 获取左侧部门数据
    getDeptDatas(node, resolve) {
      let id = 0
      if (node.data.id) {
        id = node.data.id
      }
      setTimeout(() => {
        getDeptTree(id).then(res => {
          if (resolve) {
            resolve(res.result)
          } else {
            this.deptDatas = res.result
          }
        })
      }, 100)
    },
    // 弹窗-获取首要部门
    getDepts() {
      getDeptTree(0).then(res => {
        this.depts = res.result.map(function(obj) {
          if (obj.subCount > 0) {
            obj.children = null
          }
          obj = { ...obj, label: obj.name }
          return obj
        })
      })
    },
    // 弹窗-部门数据
    loadDepts({ action, parentNode, callback }) {
      if (action === LOAD_CHILDREN_OPTIONS) {
        console.log(parentNode)
        getDeptTree(parentNode.id).then(res => {
          console.log(res)
          parentNode.children = res.result.map(function(obj) {
            if (obj.subCount > 0) {
              obj.children = null
            }
            obj = { ...obj, label: obj.name }
            return obj
          })
          setTimeout(() => {
            callback()
          }, 200)
        })
      }
    },
    //
    treeselectOn(node, instanceId) {
      this.deptCode = node.code
    },
    // 获取弹窗内角色数据
    getRoles() {
      getAll().then(res => {
        this.roles = res.result.records
      }).catch(() => { })
    },
    // 左侧-切换部门
    handleNodeClick(data) {
      if (data.pid === 0) {
        this.query.deptId = null
      } else {
        this.query.deptId = data.id
      }
      this.crud.toQuery()
    },
    checkboxT(row, rowIndex) {
      return row.id !== this.user.id
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  ::v-deep .vue-treeselect__control,::v-deep .vue-treeselect__placeholder,::v-deep .vue-treeselect__single-value {
    height: 30px;
    line-height: 30px;
  }
</style>
